package cn.zniot.so.application.util;


public class HexUtil {

	/**
	 * 
	 * @param b Java 将字节数组转成十六进制字符串
	 * @return
	 * @throws Exception
	 */
	public static String getHexString(byte[] b) throws Exception {
		String result = "";
		for (int i = 0; i < b.length; i++) {
			result += Integer.toString((b[i] & 0xff) + 0x100, 16).substring(1);
		}
		return result;
	}  

	public static String getHexString(byte b) throws Exception {
		String result = "";
		result += Integer.toString((b & 0xff) + 0x100, 16).substring(1);
		return result;
	}  
	
	/**

	　　* Convert hex string to byte[]

	　　* @param hexString the hex string

	　　* @return byte[]

	　　*/

	public static byte[] hexStringToBytes(String hexString)
	{

		if (hexString == null || hexString.equals(""))
		{
			return null;
		}

		hexString = hexString.toUpperCase();

		int length = hexString.length() / 2;

		char[] hexChars = hexString.toCharArray();

		byte[] d = new byte[length];

		for (int i = 0; i < length; i++)
		{
			int pos = i * 2;
			d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
		}
		return d;
	}

	/**

	　　* Convert char to byte

	　　* @param c char

	　　* @return byte

	　　*/

	private static byte charToByte(char c)
	{
		return (byte) "0123456789ABCDEF".indexOf(c);
	}

	
	public static byte[] HexString2Bytes(String src)
	{
		byte[] ret = new byte[6];
		byte[] tmp = src.getBytes();
		for (int i = 0; i < 6; ++i)
		{
			ret[i] = uniteBytes(tmp[i * 2], tmp[i * 2 + 1]);
		}
		return ret;
	}

	private static byte uniteBytes(byte src0, byte src1) {
	     byte _b0 = Byte.decode("0x" + new String(new byte[] {src0})).byteValue();
	     _b0 = (byte) (_b0 << 4);
	     byte _b1 = Byte.decode("0x" + new String(new byte[] {src1})).byteValue();
	     byte ret = (byte) (_b0 | _b1);
	     return ret;
	}
	
	/*
	* 将字符串编码成16进制数字,适用于所有字符（包括中文）
	*/
	public static String encode(String str) {
		String hexString="0123456789ABCDEF";
	   // 根据默认编码获取字节数组
	   byte[] bytes = str.getBytes();
	   StringBuilder sb = new StringBuilder(bytes.length * 2);
	   // 将字节数组中每个字节拆解成2位16进制整数
	   for (int i = 0; i < bytes.length; i++) {
	    sb.append(hexString.charAt((bytes[i] & 0xf0) >> 4));
	    sb.append(hexString.charAt((bytes[i] & 0x0f) >> 0));
	   }
	   return sb.toString();
	}

	
	//转化字符串为十六进制编码
	public static String toHexString(String s)   
	{   
	   String str="";   
	   for (int i=0;i<s.length();i++)   
	   {   
	    int ch = (int)s.charAt(i);   
	    String s4 = Integer.toHexString(ch);   
	    str = str + s4; 
	   }   
	   return "0x" + str;//0x表示十六进制
	}


}
